<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div style="float: left;">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="MPN" prop="mpnName">
          <el-input v-model="queryParams.mpnName" placeholder="请输入品目名称" clearable />
        </el-form-item>

        <el-form-item label="IE" prop="ie">
          <el-input v-model="queryParams.ie" placeholder="请输入IE" clearable />
        </el-form-item>

        <el-form-item label="产线" prop="line_id">
          <el-select v-model="queryParams.line_id" placeholder="请选择产线" clearable>
            <el-option v-for="item in lineList" :key="item.line_id" :label="item.line_name" :value="item.line_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-select v-model="queryParams.state" placeholder="请选择" style="width: 100px;">
            <el-option v-for="item in stateList" :key="item.state_id" :label="item.state_name" :value="item.state_id" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="selectMPNByQueryParams">搜索</el-button>
          <el-button type="primary" @click="resetButton">重置</el-button>
          <el-button type="warning" @click="LineLinkBut">产线管理</el-button>
          <el-button type="warning" @click="handleExport">导出</el-button>
        </el-form-item>
        <br>
        <el-form-item label="添加日期" prop="query_time">
          <el-date-picker v-model="queryParams.query_time" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="yyyy-MM-dd" />
        </el-form-item>


      </el-form>
      <!-- 操作按钮 -->
      <div style="float: left;margin-right: 20px;"><el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd({}, '添加MPN')" plain>新增</el-button>
          </el-col>
        </el-row></div>
      <div style="float: left;"><el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-tooltip class="item" effect="dark" content="启用会被禁用，禁用则会被启用" placement="top">
              <el-button type="warning" @click="handleState" plain>启用/禁用</el-button>
            </el-tooltip>
          </el-col>
        </el-row></div>
    </div>


    <!-- 导入Excel -->
    <div style="float: left;">
      <el-upload action="" :auto-upload="false" :show-file-list="false" :on-change="handleImport" accept=".xlsx,.xls">
        <el-button type="warning">导入Excel</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件</div>
      </el-upload>

      <!-- 下载模板 -->
      <el-button type="text" @click="downloadTemplate">下载导入模板</el-button>
    </div>



    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" height="600px" @row-dblclick="handleRowDblClick"
      @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="编号" prop="mpn_id" align="center" />
      <el-table-column label="品目名称" prop="mpn_name" align="center" />
      <el-table-column label="内部名称" prop="internal_name" align="center" />
      <el-table-column label="工程名称" prop="project_name" align="center"  width="120"/>
      <el-table-column label="工艺名称" prop="process_name" align="center"  width="120"/>
      <el-table-column label="产线" prop="line_name" align="center" />
      <el-table-column v-if="false" label="产线id" prop="line_id" align="center" />
      <el-table-column label="基准CT" prop="benchmark_value" align="center" />
      <el-table-column label="Process" prop="process" align="center"  width="120"/>
      <el-table-column label="IE" prop="ie" align="center"  width="120"/>
      <el-table-column label="负荷表组合名称" prop="ic_name" align="center"  width="180"/>
      <el-table-column label="制品长度" prop="dff" align="center" />
      <el-table-column label="psc/sheet" prop="psc_sheet" align="center" />
      <el-table-column label="设备配置" prop="device_config" align="center" />
      <el-table-column v-if="false" label="状态" prop="state" align="center" />
      <el-table-column label="部门" prop="dept_name" align="center" />
      <el-table-column label="课别" prop="class_name" align="center" />
      <el-table-column label="楼层" prop="floor" align="center" />
      <el-table-column label="BU" prop="bu" align="center" />
      <el-table-column label="添加日期" prop="insert_date" align="center" />
      <el-table-column label="禁用日期" prop="deprecated_date" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" :type="getStateButton(scope.row.state)" @click="handleDelete(scope.row)">{{
            getState(scope.row.state) }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="pageSizes"
      @pagination="selectMPNByQueryParams" />

    <!-- 产线表单 -->
    <el-dialog title="绑定产线" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form ref="form" :model="LinkForm" label-width="100px">
        <div style="float: left; margin-bottom: 15px;">
          <label style="margin-right: 10px;">请选择工号:</label>
          <el-select v-model="LinkForm.user_id" placeholder="请选择" @change="getUserLinkLine">
            <el-option v-for="item in userList" :key="item.user_id" :label="item.user_name" :value="item.user_id">
            </el-option>
          </el-select>
        </div>
        <div style="float: right;margin-bottom: 15px;" v-if="checkboxMod">
          <el-col v-for="item in lineList" :key="item.line_id" :span="12">
            <el-checkbox :label="item.line_id" v-model="checkedList">
              {{ item.line_name }}
            </el-checkbox>
          </el-col>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelLinkForm">取 消</el-button>
        <el-button type="primary" @click="setUserLinkLine">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增/修改界面 -->
    <el-dialog :title="title" :visible.sync="dialogVisibleMPNform" width="30%" :before-close="handleMPNFormClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="品目id" prop="MPN_Id" v-show="false">
          <el-input v-model="form.MPN_id" />
        </el-form-item>
        <el-form-item label="品目名称" prop="mpn_name">
          <el-input v-model="form.mpn_name" placeholder="请输入品目名称" />
        </el-form-item>
        <el-form-item label="内部名称" prop="internal_name">
          <el-input v-model="form.internal_name" placeholder="请输入内部名称" />
        </el-form-item>
        <el-form-item label="工程名称" prop="project_name">
          <el-input v-model="form.project_name" placeholder="请输入工程名称" />
        </el-form-item>
        <el-form-item label="工艺名称" prop="process_name">
          <el-input v-model="form.process_name" placeholder="请输入工艺名称" />
        </el-form-item>
        <el-form-item label="产线选择" prop="line">
          <el-select v-model="form.line" placeholder="请选择">
            <el-option v-for="item in lineList" :key="item.line_id" :label="item.line_name" :value="item.line_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基准CT" prop="benchmark_value">
          <el-input v-model="form.benchmark_value" placeholder="请输入基准CT" />
        </el-form-item>
        <el-form-item label="Process" prop="process">
          <el-input v-model="form.process" placeholder="请输入Process" />
        </el-form-item>
        <el-form-item label="IE" prop="ie">
          <el-input v-model="form.ie" placeholder="请输入IE" />
        </el-form-item>
        <el-form-item label="负荷表组合名称" prop="ic_name">
          <el-input v-model="form.ic_name" placeholder="请输入负荷表组合名称" />
        </el-form-item>
        <el-form-item label="制品长度" prop="DFF">
          <el-input v-model="form.dff" placeholder="请输入制品长度" />
        </el-form-item>
        <el-form-item label="psc/sheet" prop="psc_sheet">
          <el-input v-model="form.psc_sheet" placeholder="请输入psc/sheet" />
        </el-form-item>
        <el-form-item label="设备配置" prop="device_config">
          <el-input v-model="form.device_config" placeholder="请输入设备配置" />
        </el-form-item>
        <el-form-item label="部门" prop="dept_name">
          <el-input v-model="form.dept_name" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="课别" prop="class_name">
          <el-input v-model="form.class_name" placeholder="请输入课别" />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="form.floor" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="BU" prop="bu">
          <el-input v-model="form.bu" placeholder="请输入BU" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getMPNlist, getAllLine, getUserIdUserNameByDeptId, mpnExport,getUserLinkLine, setUserLinkLine, addMPN, selectMPNByQueryParams, exportTemplate, importExcel, setMpnState,setBatchMpnState } from "@/api/ctManage/MPNManage"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import "splitpanes/dist/splitpanes.css";
export default {
  name: "MPMManage",
  components: { Treeselect },
  data() {
    return {
      multipleSelection:[],
      //状态列表
      stateList: [
        { state_id: 1, state_name: '启用' },
        { state_id: 0, state_name: '禁用' },
        { state_id: '', state_name: '全部' }
      ],
      //部門列表
      deptList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mpnName: '',
        ie:'',
        line_id: '',
        state: '',
        query_time: []
      },
      pageSizes: [ 10, 20, 50, 100 ,200],
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 部门选项
      deptOptions: undefined,
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      dialogVisible: false,
      //  mpn添加删除
      dialogVisibleMPNform: false,
      //产线基础数据
      lineList: [],
      //存储选择
      checkedList: [],
      //部门用户
      userList: [],
      user_id: "",
      form: {},
      // 表单验证规则
      rules: {
        internal_name: [
          { required: true, message: "内部名称不能为空", trigger: "blur" },
        ],
        project_name: [
          { required: true, message: "工程名称不能为空", trigger: "blur" },
        ],
        process_name: [
          { required: true, message: "工艺名称不能为空", trigger: "blur" },
        ],
        mpn_name: [
          { required: true, message: "品目名不能为空", trigger: "blur" },
        ],
        line: [
          { required: true, message: "请选择产线", trigger: "blur" },
        ],
        benchmark_value: [
          { required: true, message: "基准CT不能为空", trigger: "blur" },
          { pattern: /^\d*\.?\d*$/, message: '只能输入数字和小数点', trigger: 'blur' }
        ],
        process: [
          { required: true, message: "process不能为空", trigger: "blur" },
        ],
        ie: [
          { required: true, message: "IE不能为空", trigger: "blur" },
        ],
        ic_name: [
          { required: true, message: "ic_name不能为空", trigger: "blur" },
        ],
        psc_sheet: [
          { pattern: /^\d*\.?\d*$/, message: '只能输入数字和小数点', trigger: 'blur' }
        ]
      },
      //产线连接表单
      LinkForm: {},
      //产线多选框
      checkboxMod: false,
      isCooldown: false, // 是否在冷却期
    };
  },
  created() {
  },
  methods: {
    //excel使用
    handleExport() {
      this.$confirm("确认导出MPN数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 调用导出接口
        mpnExport().then(response => {
          const url = URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', 'MPN.xlsx');
          document.body.appendChild(link);
          link.click();
        });
      });
    },
    //禁用启用按钮
    handleState(){
      if (this.isCooldown) {
        alert('不允许频繁操作，请稍后再试！');
        return;
      }

      // 正常逻辑（如提交数据）
      console.log('提交数据...');
      setBatchMpnState(this.multipleSelection).then(response => {})
      this.selectMPNByQueryParams()

      // 进入冷却期（10秒）
      this.isCooldown = true;

      // 10秒后恢复
      setTimeout(() => {
        this.isCooldown = false;
      }, 10000);
    },
    // 处理选择变化
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item=>[item.mpn_id,item.state])
    },
    // 设置行样式
    tableRowClassName({ row }) {
      if (row.state === 0) {
        return 'status-0-row';
        // alert(row.state)
      }
      return '';
    },
    //返回状态1启用，0禁用
    getState(value) {
      if (value) {
        return '禁用'
      } else {
        return '启用'
      }
    },
    //返回状态1启用，0禁用
    getStateButton(value) {
      if (value) {
        return 'danger'
      } else {
        return 'success'
      }
    },
    //表格链接
    setUserLinkLine() {
      if (this.LinkForm.user_id != null) {
        setUserLinkLine(this.LinkForm.user_id, this.checkedList);
        this.$message.success("添加成功");
        this.cancelLinkForm();
      } else {
        this.$message.err("请选择工号");
      }


    },
    //调用链接
    getUserLinkLine() {
      this.checkboxMod = true;
      getUserLinkLine(this.LinkForm.user_id).then(response => {
        this.checkedList = response
      })
    },
    //修改/写入Link表
    submitLinkForm() { },
    //产线管理按钮
    LineLinkBut() {
      this.dialogVisible = true;

    },
    //获得使用部门的用户
    getUserList() {
      getUserIdUserNameByDeptId().then(response => {
        this.userList = response
      })
    },
    //获取全部产线
    getAllLine() {
      getAllLine().then(response => {
        this.lineList = response;
      })
    },
    //查询MPN
    getMPNlistBut() {
      this.tableData = [];
      getMPNlist(this.queryParams.pageNum, this.queryParams.pageSize).then(response => {
        this.total = response.total;
        for (let index = 0; index < response.list.length; index++) {
          const element = response.list[index];
          this.tableData.push(
            {
              mpn_id: element.mpn_id,
              internal_name: element.internal_name,
              project_name: element.project_name,
              process_name: element.process_name,
              line_name: element.line.line_name,
              line: element.line.line_id,
              mpn_name: element.mpn_name,
              benchmark_value: element.benchmark_value,
              process: element.process,
              ic_name: element.ic_name,
              psc_sheet: element.psc_sheet,
              device_config: element.device_config,
              state: element.state,
              dept_name: element.dept_name,
              class_name: element.class_name,
              floor: element.floor,
              NPI: element.npi,
              dff: element.dff,
              ie: element.ie,
              bu: element.bu,
              insert_date: element.insert_date,
              deprecated_date: this.deprecatedDate(element.deprecated_date)
            })
        }
      })
    },
    //条件查询MPN
    selectMPNByQueryParams() {
      this.tableData = [];
      selectMPNByQueryParams(this.queryParams.pageNum,
        this.queryParams.pageSize,
        this.queryParams.mpnName,
        this.queryParams.ie,
        this.queryParams.line_id,
        this.queryParams.state,
        this.queryParams.query_time[0], this.queryParams.query_time[1]).then(response => {
          this.total = response.total;
          for (let index = 0; index < response.list.length; index++) {
            const element = response.list[index];
            this.tableData.push(
              {
                mpn_id: element.mpn_id,
                internal_name: element.internal_name,
                project_name: element.project_name,
                process_name: element.process_name,
                line_name: element.line.line_name,
                line: element.line.line_id,
                mpn_name: element.mpn_name,
                benchmark_value: element.benchmark_value,
                process: element.process,
                ic_name: element.ic_name,
                psc_sheet: element.psc_sheet,
                device_config: element.device_config,
                state: element.state,
                dept_name: element.dept_name,
                class_name: element.class_name,
                floor: element.floor,
                NPI: element.npi,
                dff: element.dff,
                ie: element.ie,
                bu: element.bu,
                insert_date: element.insert_date,
                deprecated_date: this.deprecatedDate(element.deprecated_date)
              })
          }
        })
    },
    //禁用日期处理
    deprecatedDate(value) {
      if (value != null) {
        return value;
      } else {
        return '暂无';
      }

    },
    //重置
    resetButton() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        mpn_name: '',
        line_id: '',
        state: '',
        query_time: []
      }
    },

    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 双击行处理方法
    handleRowDblClick(row, column, event) {
      if (row.state) {
        this.handleAdd(row, '修改');
      } else {
        alert("已停用")
      }

    },
    // 新增按钮
    handleAdd(data, title) {
      this.dialogVisibleMPNform = true;
      // 清空表单
      this.form = data;
      this.title = title;
    },
    // 编辑按钮
    handleEdit(row) {
      this.resetForm();
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = "修改样本";
    },
    // 修改组状态按钮
    handleDelete(row) {
      var state;
      if (row.state) {
        state = '禁用'
      } else {
        state = '启用'
      }
      this.$confirm('确认' + state + '该样本？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          setMpnState(row.mpn_id, row.state).then(response => {
            if (response > 0) {
              this.$message.success(state + "成功");
              this.selectMPNByQueryParams();
            } else {
              this.$message.error(state + "失败");
            }
          })
        })
        .catch(() => { });

    },
    // 表单提交
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addMPN(this.form).then(response => {
            if (response > 0) {
              this.$message.success("添加成功");
              this.getMPNlistBut();
            } else {
              this.$message.error("添加失败");
            }
          })
          this.dialogVisibleMPNform = false;

        }
      });
    },
    // 取消链接按钮
    cancelLinkForm() {
      this.checkboxMod = false;
      this.dialogVisible = false;
      this.resetLinkForm();
    },
    // 取消按钮
    cancel() {
      this.dialogVisibleMPNform = false;
      this.form = {};
    },
    // 重置链接表单
    resetLinkForm() {
      this.LinkForm = {};
      this.checkedList = [];
    },
    //關閉表單
    handleClose() {
      this.checkboxMod = false;
      this.dialogVisible = false;
      this.resetLinkForm();
    },
    //關閉表單
    handleMPNFormClose() {
      this.form = {};
      this.dialogVisibleMPNform = false;
    },

    //导入
    handleImport(file) {
      const formData = new FormData();
      formData.append("file", file.raw);
      importExcel(formData).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.selectMPNByQueryParams();
      }).catch(error => {
        this.$modal.msgError(error);
      });
    },

    //导入模板
    downloadTemplate() {
      exportTemplate().then(res => {
        // 处理blob下载
        const blob = new Blob([res], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = '数据导入模板.xlsx';
        link.click();
      });

    }

  },

  mounted() {
    this.getMPNlistBut();
    this.getAllLine();
    this.getUserList();
  },
};
</script>

<style scoped>
/* 表格滚动条样式 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 12px;
  /* 纵向滚动条宽度 */
  height: 12px;
  /* 横向滚动条高度 */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  /* 滚动条滑块颜色 */
  border-radius: 4px;
  /* 滚动条滑块圆角 */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
  /* 鼠标悬停时滚动条滑块颜色 */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: #f5f5f5;
  /* 滚动条轨道颜色 */
  border-radius: 4px;
  /* 滚动条轨道圆角 */
}
/* 状态样式 */
::v-deep .el-table .status-0-row {
  background-color: rgb(183, 183, 183);
}

::v-deep .status-0-row:hover>td {
  background-color: rgb(183, 183, 183) !important;
}
</style>